package com.basker.pisces.springcloud.locale;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.LocaleUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.basker.pisces.context.LoginContext;
import com.basker.pisces.context.LoginContextHolder;
import com.basker.pisces.service.constant.ServiceConstants;

/**
 * 请求拦截器，用于设置当前语言，优先从LoginContext获取，没有的话再从消息头中获取
 *
 * @author hangwen
 */
public class ServiceLocaleInterceptor extends HandlerInterceptorAdapter {

    private static final String LOCAL_PARAM_NAME = ServiceConstants.MessageHead.LOCAL_KEY;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Locale locale = this.tryGetLocaleFromLoginContext();
        if (locale != null) {
            LocaleContextHolder.setLocale(locale, true);
            return true;
        }

        locale = this.tryGetLocaleFromFromHeader(request);
        if (locale != null) {
            LocaleContextHolder.setLocale(locale, true);
            return true;
        }

        return true;
    }

    private Locale tryGetLocaleFromFromHeader(HttpServletRequest request) {
        String localeStr = request.getHeader(LOCAL_PARAM_NAME);

        if (!StringUtils.isEmpty(localeStr)) {
            return LocaleUtils.toLocale(localeStr);
        }

        return null;
    }

    private Locale tryGetLocaleFromLoginContext() {
        LoginContext loginContext = LoginContextHolder.getLoginContext();
        if (loginContext == null) {
            return null;
        }

        return loginContext.getLocaleObject();
    }

}
